package algorithm

import "fmt"

// Rotate 给一个正方形 N*N 矩阵, 求旋转之后的, 原地调整; no idea;
// T1: 顺时针旋转90度正方形, 原地调整
func Rotate(s [][]int) [][]int {
	var (
		l    = len(s) - 1
		a, b = 0, 0
		c, d = l, l
	)

	for a < c {
		s = RotateEdge(s, a, b, c, d)
		a++
		b++
		c--
		d--
	}

	return s
}

func RotateEdge(s [][]int, a, b, c, d int) [][]int {
	for i := 0; i < d-b; i++ {
		tmp := s[a][b+i]
		s[a][b+i] = s[c-i][b]
		s[c-i][b] = s[c][d-i]
		s[c][d-i] = s[a+i][d]
		s[a+i][d] = tmp
	}

	return s
}

// 拿到这个题 总是想怎么调整的; 要有宏观思维

// PrintMatrixZigZag 旋转打印矩形
func PrintMatrixZigZag(matrix [][]int) {
	var (
		a, b  = 0, 0
		c, d  = 0, 0
		m     = len(matrix) - 1    // m行 用来 ac
		n     = len(matrix[0]) - 1 // n列 用于约束 bd
		upper = true
	)

	for c != m+1 {
		PrintLine(matrix, a, b, c, d, upper)
		// move A
		if a < m {
			a++
		} else {
			b++
		}

		// move C
		if d < n {
			d++
		} else {
			c++
		}

		upper = !upper
	}
}

func PrintLine(m [][]int, a, b, c, d int, upper bool) {
	if upper {
		for a >= c {
			fmt.Print(m[a][b], " ")
			a--
			b++
		}
	} else {
		for d >= b {
			fmt.Print(m[c][d], " ")
			c++
			d--
		}
	}

	fmt.Println()
}
